package core.genetic.selection;

import java.util.Arrays;

import utility.Pair;
import utility.Utils;
import core.Mode;
import core.genetic.Individual;
import core.genetic.Population;

public class RouletteWheelSelection implements Selection{

		final double keeprate;	//procenat roditelja koji prezivljava i pari se
		
		public RouletteWheelSelection(double keeprate) {
			this.keeprate = keeprate;
		}
		
		public void select(Population pop, double[] values) {
			int length = values.length;
			Pair<Individual, Double>[] par = (Pair<Individual, Double>[])new Pair<?,?>[values.length];
			for (int i=0; i<values.length; i++){
				par[i] = new Pair<Individual, Double>(pop.get(i), values[i]);
			}
			Arrays.sort(par, new Pair.SecondDescendingComparator<Individual, Double>());
						
			int parent = (int) (keeprate*length);
			
			double[] cumProb = Utils.calcCumulativeProb(par, parent);
			for (int i=parent; i<length; i++){
				int cale = Utils.randomW(cumProb);
				int keva = Utils.randomW(cumProb);
				for(int j = 0;cale==keva && j<10;j++)
					keva = Utils.randomW(cumProb);
				Individual ind = Mode.mode.crossover.crossover(par[cale].first(), par[keva].first());
				par[i].first().set(ind);
			}
			pop.setFirst(par, length);
			
			for(int i = (int)(0.5+Mode.mode.elitismRate*pop.size());i<pop.size();i++) 			
				Mode.mode.mutation.mutate(pop.get(i));

		}


}
